package com.jingwu.nacos;

import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.util.Objects;

@SpringBootApplication
public class NacosConfigReadApplication {

    public static void main(String[] args) {
        SpringApplication.run(NacosConfigReadApplication.class, args);
    }

    @Autowired
    private ObjectMapper objectMapper;

    @Value("${nacos.server-addr}")
    private String serverAddr;

    @Value("${nacos.group}")
    private String group;

    @RestController
    public class TestController {

        @SneakyThrows
        @GetMapping("/test/read")
        public Mono<Rule> read() {
            ConfigService configService = ConfigFactory.createConfigService(serverAddr);
            String routerConfig = configService.getConfig(group + ":" + "route", group, 3000);
            if (StringUtils.isBlank(routerConfig)) {
                return Mono.empty();
            }
            return Mono.just(objectMapper.readValue(routerConfig, Rule.class));
        }
    }

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }

    @Data
    public static class Rule {
        private String name;
        private String routerId;
        private String path;
    }

}
